package cn.com.cetccst.compliancecheck.checker;

import static cn.com.cetccst.tools.kv.CommonKV.kvStore;

import android.content.Context;
import android.text.format.DateUtils;

import cn.com.cetccst.compliancecheck.R;
import cn.com.cetccst.compliancecheck.kv.KVKeys;
import cn.com.cetccst.tools.log.CommonLogger;

public class ConnectionChecker extends Checker {

    private int intervalHours;
    private static ConnectionChecker instance;

    private ConnectionChecker(Context context) {
        super(CheckerType.Connection);
        name = context.getString(R.string.compliance_connection);
    }

    public static void init(Context context) {
        if(instance == null) {
            instance = new ConnectionChecker(context);
        }
    }

    public static ConnectionChecker getInstance() {
        return instance;
    }

    @Override
    public void check(Context context) {
        CommonLogger.info("Start check connection");
        super.check(context);
        if(!isEnable())
            return;
        long lastCheckInTime = kvStore.decodeLong(KVKeys.KEY_LAST_CHECK_IN_TIME);
        if (lastCheckInTime == -1) {
            CommonLogger.warn("consider device is not violated since never check in.");
            setResult(CheckResult.Pass);
        }
        long currentTime = System.currentTimeMillis();
        long offlinePeriod = currentTime - lastCheckInTime;
        long maxLimit = intervalHours * DateUtils.HOUR_IN_MILLIS;
        if (offlinePeriod > maxLimit) {
            CommonLogger.warn("Connectivity is violated due to offline days reach limit: " + maxLimit
                    + ", offlinePeriod:" + offlinePeriod);
            setResult(CheckResult.Violated);
        }
    }

    public int getIntervalHours() {
        return intervalHours;
    }

    public void setIntervalHours(int intervalHours) {
        this.intervalHours = intervalHours;
    }
}
